<?php

namespace app\admin\validate\shop\advert;

use app\admin\model\shop\goods\Goods;
use app\shop\enums\goods\GoodsStatus;
use think\Validate;

class Banner extends Validate
{
    protected $failException = true;

    /**
     * 验证规则
     */
    protected $rule = [
        'jump' => 'checkGoodsId',
    ];

    /**
     * 提示消息
     */
    protected $message = [
        'jump.checkGoodsId' => '请选择有效的跳转商品',
    ];

    /**
     * 验证场景
     */
    protected $scene = [
        'add'  => ['jump'],
        'edit' => ['jump'],
    ];

    protected function checkGoodsId($value, $rule, $data = []): bool
    {
        if (intval($value)) {
            if (empty($data['goods_id'])) {
                $goodsId = \app\admin\model\shop\advert\Banner::where('id', $data['id'])->value('goods_id');
            } else {
                $goodsId = $data['goods_id'];
            }
            $goods = Goods::where(['id' => $goodsId])->findOrEmpty();
            if ($goods->isEmpty() || $goods->status === GoodsStatus::OFF_SHELF) {
                return false;
            }
            return true;
        }

        return true;
    }
}
